package com.shareach.redis;

import org.apache.commons.pool.BasePoolableObjectFactory;

import redis.clients.util.Pool;

public class NewJedisPool extends Pool<NewJedis>{

	private static class JedisFactory extends BasePoolableObjectFactory<NewJedis>{

        public NewJedis makeObject()
            throws Exception
        {
            NewJedis jedis;
            if(timeout > 0)
                jedis = new NewJedis(host, port, timeout);
            else
                jedis = new NewJedis(host, port);
            jedis.connect();
            if(null != password)
                jedis.auth(password);
            return jedis;
        }

        public void destroyObject(NewJedis jedis) throws Exception{
            if(jedis.isConnected())
               try{
                  try{
                      jedis.quit();
                  }
                  catch(Exception e) { 
                	  
                  }
                  jedis.disconnect();
                }
                catch(Exception e) { 
                	
                }
        }

        public boolean validateObject(NewJedis jedis){
           try{
              return jedis.isConnected() && jedis.ping().equals("PONG");
           }
           catch(Exception e){
              return false;
           }
            
        }

        private final String host;
        private final int port;
        private final int timeout;
        private final String password;

        public JedisFactory(String host, int port, int timeout, String password){
            this.host = host;
            this.port = port;
            this.timeout = timeout <= 0 ? -1 : timeout;
            this.password = password;
        }
    }


    public NewJedisPool(org.apache.commons.pool.impl.GenericObjectPool.Config poolConfig, String host){
        this(poolConfig, host, 6379, 2000, null);
    }

    public NewJedisPool(String host, int port){
        super(new org.apache.commons.pool.impl.GenericObjectPool.Config(), new JedisFactory(host, port, 2000, null));
    }

    public NewJedisPool(org.apache.commons.pool.impl.GenericObjectPool.Config poolConfig, String host, int port, int timeout, String password){
        super(poolConfig, new JedisFactory(host, port, timeout, password));
    }

    public NewJedisPool(org.apache.commons.pool.impl.GenericObjectPool.Config poolConfig, String host, int port){
        this(poolConfig, host, port, 2000, null);
    }

    public NewJedisPool(org.apache.commons.pool.impl.GenericObjectPool.Config poolConfig, String host, int port, int timeout){
        this(poolConfig, host, port, timeout, null);
    }
}
